package main

import (
	"flag"
	"geekbang-go-homework/week04/internal/conf"
	"geekbang-go-homework/week04/pkg/app"
	"geekbang-go-homework/week04/pkg/config"
	"geekbang-go-homework/week04/pkg/transport/grpc"
	"geekbang-go-homework/week04/pkg/transport/http"
	"time"

	"go.uber.org/zap/zapcore"

	"go.uber.org/zap"
	"go.uber.org/zap/zapgrpc"
	"google.golang.org/grpc/grpclog"
)

var configPath string

func init() {
	// 设置时区
	locationShanghai, err := time.LoadLocation("Asia/Shanghai")
	if err != nil {
		panic(err)
	}
	time.Local = locationShanghai
	// 解析命令行参数 -conf 指定配置文件路径
	flag.StringVar(&configPath, "conf", "../../configs", "config path, eg: -conf config.yaml")
}

func main() {
	flag.Parse()
	// 加载解析配置文件
	boot := &conf.Bootstrap{}
	if err := config.LoadConfig(configPath, boot); err != nil {
		panic(err)
	}
	log := newLogger()
	app, cancel, err := initApp(boot, log)
	if err != nil {
		panic(err)
	}
	defer cancel()
	if err = app.Run(); err != nil {
		log.Error(err)
	}
}

func newApp(log grpclog.LoggerV2, grpc *grpc.Server, http *http.Server) *app.App {
	a := app.NewApp(
		app.WithLogger(log),
		app.WithServers(grpc, http),
	)
	return a
}

func newLogger() grpclog.LoggerV2 {
	zapConfig := zap.NewProductionConfig()
	zapConfig.Encoding = "console"
	zapConfig.EncoderConfig.EncodeTime = func(t time.Time, encoder zapcore.PrimitiveArrayEncoder) {
		encoder.AppendString(t.Format("2006-01-02 15:04:05"))
	}
	zapLog, err := zapConfig.Build(
		zap.AddCallerSkip(1),
	)
	if err != nil {
		panic(err)
	}
	return zapgrpc.NewLogger(zapLog)
}
